<template>
  <div>
    <photo-view :list="list" @close="close" :isShare="false" />
    <el-card>
      <el-tabs class="demo-tabs" v-model="tabId" @tab-change="tabChange">
        <el-tab-pane v-for="(item, index) in myFormList" :label="item.tableName" :name="item.tFId" :key="index">
          <div :id="'dataFormMainBox' + item.tFId">
            <comMy :params="item" :tFId="item.tFId" v-if="tabId == item.tFId" :isFormList="true" ref="tableRef"
              @returnFormulaList="getFormulaList" @returnEventResultBtn="handleEventResultBtn" />
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-row style="justify-content: end">
        <el-form-item label="公式列表：" prop="formula" label-width="80" v-if="formulaList.length">
          <el-select v-model="formula" style="width: 500px" clearable filterable>
            <el-option v-for="item in formulaList" :key="item.formulaId" :value="item.formulaId"
              :label="item.formulaExpressDisplay">
              <el-tooltip class="box-item" effect="customized" placement="top" :content="item.formulaExpressDisplay">
                <div style="
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                      ">
                  {{ item.formulaExpressDisplay }}
                </div>
              </el-tooltip>
            </el-option>
          </el-select>
        </el-form-item>
        <el-button type="success" @click="eventResult"
          v-if="userStepId == 0 && userStatus == 0 && (eventResultBtn || formulaList.length > 0)">计算结果</el-button>
        <el-button style="background-color: #6200ff; color: #fff" @click="handleUseRecord">仪器使用记录</el-button>
        <el-button style="background-color: #6200ff; color: #fff" @click="handleZp(35)">{{ userStepId !== 0 ||
      userStatus == 1 ? "查看" : "上传" }}现场照片</el-button>
        <el-button style="background-color: #6200ff; color: #fff" @click="handleZp(41)">{{
      userStepId !== 0 || userStatus == 1 ? "查看" : "上传"
    }}点位示意图</el-button>
        <el-button style="background-color: #e6a23c; color: #fff" @click="handleDataRel"
          v-if="userStatus == 0">数据引用</el-button>
        <el-button type="success" @click="saveData(false)" v-if="userStatus == 0">保 存</el-button>
        <el-dropdown split-button type="success" @click="submitData(1)" style="margin: 0 10px"
          v-if="userStatus == 0 && userStepId !== 2">
          提交
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="submitData(1)">
                <el-button type="success" link>随机审核</el-button>
              </el-dropdown-item>
              <el-dropdown-item @click="submitData(2)">
                <el-button type="success" link>手动审核</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="success" v-if="userStatus == 0 && userStepId == 2" @click="submitData(1)">完成</el-button>
        <el-button type="success" @click="returnWrite" v-if="isException || (userStatus == 0 && userStepId > 0)">
          退回给填报员
        </el-button>
        <el-dropdown split-button type="success" @click="submitData(1)">
          更多操作
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="showRecord">
                流程记录
              </el-dropdown-item>
              <el-dropdown-item @click="printDateForm">
                打印
              </el-dropdown-item>
              <el-dropdown-item @click="exportDateFormPdf">
                导出pdf
              </el-dropdown-item>
              <el-dropdown-item @click="handleReloadTable" v-if="userStatus == 0 && userStepId == 0">
                重载数据
              </el-dropdown-item>
              <el-dropdown-item @click="handleArchiveTable" v-if="isException && (userStatus == 1 && userStepId > 0)">
                重载数据
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-row>
    </el-card>
    <!-- 流程记录 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable v-model="recordOpen"
      :title="recordTitle" width="950">
      <el-table :data="recordList" v-loading="loadingRecord" max-height="60vh">
        <el-table-column label="步骤" align="center">
          <template #default="scope">
            <span v-if="scope.row.userStepId == 0">现场填报</span>
            <span v-if="scope.row.userStepId == 1">复核</span>
            <span v-if="scope.row.userStepId == 2">审核</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="nickName" align="center" />
        <el-table-column label="开始时间" prop="createTime" align="center" />
        <el-table-column label="结束时间" prop="finishTime" />
        <el-table-column label="状态">
          <template #default="scope">
            <span v-if="scope.row.userStatus == 0">未完成</span>
            <span v-if="scope.row.userStatus == 1">已完成</span>
            <span v-if="scope.row.userStatus == 2">退回</span>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="recordOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="fjOpen" :title="myTypeId == 35 ? '现场照片' : '点位示意图'">
      <el-row>
        <p class="pinformation">{{ myTypeId == 35 ? "现场照片" : "点位示意图" }}列表</p>
        <p class="totalStyle">共 {{ annexList.length }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 20px">
          <el-button type="success" link @click="handleAnnexAdd"
            v-if="userStepId === 0 && userStatus === 0">新增</el-button>
        </el-row>
      </el-row>
      <el-table ref="projectRef" :data="annexList" v-loading="annexLoading" height="25vh">
        <el-table-column label="序号" type="index" width="70" align="center" />
        <el-table-column label="文件名称" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span @click="list = [{ fileId: scope.row.fileId, fileName: scope.row.fileName }]" class="fileNameHover">{{
      scope.row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">
            <el-button link type="success" icon="Edit" @click="editAnnex(scope.row)"
              v-if="userStepId === 0 && userStatus === 0">编辑</el-button>
            <el-button link type="success" icon="Edit" @click="editAnnex(scope.row)" v-else>查看</el-button>
            <el-button link type="success" icon="Delete" @click="deleteAnnex(scope.row)"
              v-if="userStepId === 0 && userStatus === 0">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="annexOpen" :title="annexTitle" width="500px" @close="annexClose">
      <el-form :model="annexForm" ref="annexRef" label-width="80">
        <fileUpload v-model="annexForm.fileList" :fileType="['jpg', 'bmp', 'png']" :autoUpload="true"
          :fileId="annexForm.fileId" :isDisplay="!userStepId"></fileUpload>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="annexSave">保存</el-button>
          <el-button type="danger" @click="annexOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="submitOpen" :title="submitTitle" width="700px" @close="submitClose">
      <el-row justify="center">
        <el-col :span="4" style="padding-left: 10px; padding-top: 10px">
          <el-steps direction="vertical" :active="userStepId + 1">
            <el-step title="填报" />
            <el-step title="复核" />
            <el-step title="审核" />
          </el-steps>
        </el-col>
        <el-col :span="20" class="dialogUser">
          <el-input style="margin-bottom: 10px" v-model="filterText" clearable placeholder="请输入人员名称"
            prefix-icon="UserFilled">
          </el-input>
          <el-scrollbar height="50vh" ref="scrollbarRef">
            <el-tree :data="treeData" :props="defaultProps" :default-expand-all="true" @node-click="nodeClick"
              node-key="userId" :highlight-current="true" ref="treeRef" v-loading="treeLoading"
              :filter-node-method="filterNode" />
          </el-scrollbar>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitConfirm">确认</el-button>
          <el-button type="danger" @click="submitOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <instrumentDia :lMId="taskId" :useTypeId="useTypeId" @save="save" ref="instrumentRef" />
  </div>
</template>

<script setup>
import instrumentDia from "@/components/instrument/index";
import {
  getTableDataByTask,
  myTaskFormListByTaskId,
  returnWriteData,
  userRecordList,
  approveData,
  reloadArchiveFile
} from "@/api/myTask/myTask";
import { listAnnex, delAnnex, formAnnex, saveAnnex } from "@/api/lab/labMethod";
import bus from "@/utils/eventBus";
import comMy from "./comMy.vue";
import { getTreeList } from "@/api/system/newUser";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance();
const route = useRoute();
const tabId = ref();
const myId = ref(route.query.procInsId);
const taskId = ref("");
const myFormList = ref();
const userStatus = ref(0);
const userStepId = ref(0);
const recordOpen = ref(false);
const isSave = ref(false);
const recordTitle = ref("流程记录");
const recordList = ref([]);
const loadingRecord = ref(false);
const nextUser = ref({});
const tableRef = ref(null);
const eventResultBtn = ref(false);
const useTypeId = ref(0);
const isException = ref(false); //是否是异常数据,异常数据三审后也可能退回
const formulaList = ref([]);
const formula = ref();
const isView = ref(false);
const props = defineProps({
  myId: {
    type: String, //参数类型
  },
});

defineExpose({
  getInfo,
});

watch(
  () => props.myId,
  (val) => {
    myId.value = props.myId;
    isSave.value = false;
    handleMyFormList();
  }
);

nextTick(() => {
  if (route.query.procInsId) {
    isSave.value = false;
    handleMyFormList();
  }
});

function getInfo(val, exception) {
  isView.value = true;
  myTaskFormListByTaskId(val)
    .then((res) => {
      myId.value = res.data.myId;
      res.data.myTaskFormList.forEach(item => {
        item.userStatus = 1;
      })
      myFormList.value = res.data.myTaskFormList;
      userStatus.value = 1;//从此函数（getInfo）进度的说明是查看。
      userStepId.value = res.data.userStepId;
      nextTick(() => {
        tabId.value = myFormList.value[0].tFId;
        taskId.value = myFormList.value[0].taskId;
      });
      if (exception) {
        isException.value = exception;
      }
    })
    .catch((res) => {
      myFormList.value = {};
    });
  return;
}

function reset() {
  if (formulaList.value && formulaList.value.length > 0) {
    formulaList.value = [];
  }
  if (formula.value) {
    formula.value = undefined;
  }
}
function handleMyFormList() {
  reset();
  getTableDataByTask(myId.value)
    .then((res) => {
      if (!res.data) {
        return;
      }
      myFormList.value = res.data.myTaskFormList;
      userStatus.value = res.data.userStatus;
      userStepId.value = res.data.userStepId;
      if (res.data.nextUserId) {
        nextUser.value.nextUserId = res.data.nextUserId;
        nextUser.value.nextUserName = res.data.nextNickName;
      }
      nextTick(() => {
        tabId.value = myFormList.value[0].tFId;
        taskId.value = myFormList.value[0].taskId;
      });
    })
    .catch((res) => {
      myFormList.value = {};
    });
}

function saveData(val) {
  bus.emit("saveData", val);
}

function handleDataRel() {
  bus.emit("dataRel");
}

// -------------------------------------------手动审核------------------------------------------
const submitOpen = ref(false);
const submitTitle = ref("选择提交人");
const treeData = ref([]);
const defaultProps = ref({ label: "nickName", children: "children" });
const treeLoading = ref(false);
const userId = ref("");
const filterText = ref("");

function submitClose() {
  filterText.value = "";
  userId.value = "";
  treeData.value = [];
}
function confirmSubmitData(tableData) {
  bus.emit("getData", tableData);
  if (tableData.length == 0) {
    proxy.$modal.msgError("获取表单数据失败，请联系管理员！");
    return;
  }
  if (typeof tableData.data == "string" && tableData.data.indexOf("warning") != -1) {
    proxy.$modal
      .confirm(tableData.data.substring(8) + "确认要继续吗？")
      .then(function () {
        confirmSubmitData({ isValidate: true, ignore: true });
      })
      .catch(() => { });
    return;
  }
  if (typeof tableData.data === "boolean" && !tableData.data) {
    return;
  }
  approveData(tableData.data).then((res) => {
    proxy.$modal.msgSuccess("提交成功！");
    if (route.query.procInsId) {
      bus.emit("dbSave");
      proxy.$tab.closePage().then(() => {
        proxy.$router.push(route.query.path);
      });
    } else {
      userStatus.value = 1;
      bus.emit("showTable");
      bus.emit("localWriteRefresh");
    }
  });
}
function submitData(bs) {
  if (bs == 1) {
    proxy.$modal.confirm("确认要提交吗？").then(function () {
      let tableData = { isValidate: true };
      confirmSubmitData(tableData);
    });
  } else {
    submitOpen.value = true;
    treeLoading.value = true;
    getTreeList().then((res) => {
      treeData.value = proxy.handleTree(res.data, "userId");
      treeLoading.value = false;
      if (nextUser.value.nextUserId) {
        nextTick(() => {
          filterText.value = nextUser.value.nextUserName;
        });
      }
    });
  }
}

function nodeClick(val) {
  userId.value = "";
  if (val.userType == 1) {
    userId.value = val.userId;
  }
}

function submitConfirm() {
  if (!userId.value) {
    proxy.$modal.msgError("请选择提交人");
    return;
  }
  proxy.$modal.confirm("确认要提交吗？").then(function () {
    let tableData = { isValidate: true };
    bus.emit("getData", tableData);
    if (tableData.length == 0) {
      proxy.$modal.msgError("获取表单数据失败，请联系管理员！");
    }
    if (typeof tableData.data === "boolean" && !tableData.data) {
      return;
    }
    tableData.data.userId = userId.value;
    approveData(tableData.data).then((res) => {
      proxy.$modal.msgSuccess("提交成功！");
      submitOpen.value = false;
      if (route.query.procInsId) {
        bus.emit("dbSave");
        proxy.$tab.closePage().then(() => {
          proxy.$router.push(route.query.path);
        });
      } else {
        userStatus.value = 1;
        bus.emit("showTable");
        bus.emit("localWriteRefresh");
      }
    });
  });
}

function filterNode(value, data) {
  if (!value) {
    return true; // 如果搜索框为空，则显示所有节点
  }
  return data.nickName.includes(value) || data.userId.includes(value); // 根据节点的 groupName 属性进行名称过滤
}

watch(
  () => filterText.value,
  (val) => {
    proxy.$refs["treeRef"].filter(val);
  }
);

function handleReloadTable() {
  bus.emit("handleReloadTable");
}

function handleArchiveTable() {
  reloadArchiveFile(myId.value).then((res) => {
    proxy.$modal.msgSuccess("重载成功！");
    getInfo(taskId.value, isException.value)
  });
}

function returnWrite() {
  proxy.$modal.confirm("确认要退回给填报员吗？").then(function () {
    let tableData = {};
    bus.emit("getData", tableData);
    if (tableData.length == 0) {
      proxy.$modal.msgError("获取表单数据失败，请联系管理员！");
    }
    if (isException.value) {
      tableData.data.isException = isException.value;
    }
    returnWriteData(tableData.data).then((res) => {
      proxy.$modal.msgSuccess("提交成功！");
      userStatus.value = 1;
      if (isException.value) {
        emits("callback");
        return;
      }
      try {
        bus.emit("closeDialog");
      } catch (e) {
        bus.emit("showTable");
      }
    });
  });
}

function showRecord() {
  recordOpen.value = true;
  loadingRecord.value = true;
  userRecordList(myId.value).then((res) => {
    recordList.value = res.data;
    loadingRecord.value = false;
  });
}

function printDateForm() {
  bus.emit("printDateForm");
}

function exportDateFormPdf() {
  proxy.download(
    "/lims/tablePdf/pcViewPdf/" + taskId.value + "/" + myId.value,
    {},
    `现场记录表.pdf`
  );
}

// ---------------------------仪器使用记录--------------------------
const instrumentRef = ref([]);
function handleUseRecord() {
  if (userStatus.value == 0 && userStepId.value == 0) {
    instrumentRef.value.handleUseRecord();
  } else {
    instrumentRef.value.handleUseRecord(true);
  }
}
// ---------------------------------上传附件---------------------------

const fjOpen = ref(false);
const myTypeId = ref("");
function handleZp(typeId) {
  fjOpen.value = true;
  myTypeId.value = typeId;
  annexLoading.value = true;
  listAnnex({ groupId: taskId.value, typeId: typeId }).then((res) => {
    annexLoading.value = false;
    annexList.value = res.data;
  });
}

const annexOpen = ref(false);
const annexLoading = ref(false);
const annexTitle = ref("");
const annexForm = ref({ fileList: [] });
const annexList = ref([]);

function annexClose() {
  annexForm.value = { fileList: [] };
}

function annexSave() {
  if (!annexForm.value.fileId) {
    annexForm.value.fileId = annexForm.value.fileList[0].fileId;
  }
  annexForm.value.groupId = taskId.value;
  annexForm.value.typeId = myTypeId.value;
  annexForm.value.fileName = annexForm.value.fileList[0].fileName;
  annexForm.value.fileSizeDisplay = annexForm.value.fileList[0].fileSizeDisplay;
  delete annexForm.value.fileList;
  saveAnnex(annexForm.value).then((res) => {
    annexOpen.value = false;
    annexTitle.value = "";
    proxy.$modal.msgSuccess("保存成功");
    annexLoading.value = true;
    listAnnex({ groupId: taskId.value, typeId: myTypeId.value }).then((res) => {
      annexLoading.value = false;
      annexList.value = res.data;
    });
  });
}

function eventResult() {
  tableRef.value[0].eventResult();
}

function handleEventResultBtn(isShow) {
  eventResultBtn.value = isShow;
}

function handleAnnexAdd() {
  annexOpen.value = true;
  debugger;
  annexTitle.value = "新增" + (myTypeId.value == 35 ? "现场照片" : "点位示意图");
  nextTick(() => {
    proxy.$refs["annexRef"].clearValidate();
  });
}

function deleteAnnex(row) {
  proxy.$modal.confirm("确定要删除吗？").then(() => {
    delAnnex(row.fileId).then((res) => {
      annexLoading.value = true;
      listAnnex({ groupId: taskId.value, typeId: myTypeId.value }).then((res) => {
        annexLoading.value = false;
        annexList.value = res.data;
      });
    });
  });
}

function editAnnex(row) {
  formAnnex(row.fileId).then((res) => {
    annexTitle.value = "编辑附件";
    annexOpen.value = true;
    annexForm.value = {
      fileList: [
        {
          fileName: res.data.fileName,
          fileId: res.data.fileId,
          fileSizeDisplay: res.data.fileSizeDisplay,
        },
      ],
      groupId: res.data.groupId,
      fileId: res.data.fileId,
      typeId: res.data.typeId,
    };
    nextTick(() => {
      proxy.$refs["annexRef"].clearValidate();
    });
  });
}

function tabChange(name) {
  if (userStatus.value == 0) {
    // if (isSave.value) {
    saveData(true);
    // }
    isSave.value = true;
  }
}

function save(sourceFlag) {
  if (sourceFlag && typeof sourceFlag == 'string') {
    saveData(sourceFlag);
  } else {
    saveData(true);
  }
}

const list = ref([]);
function close() {
  list.value = [];
}

function getFormulaList(list) {
  if (list.length > 0) {
    formulaList.value = list;
    formula.value = list[0].formulaId;s
  }
}

const emits = defineEmits(["callback"]);
</script>
<style>
/** 解决手动选择人员框时 el-scrollbar遮挡footer中的按钮导致无法点击*/
.dialogUser .el-scrollbar {
  height: 90%;
}
</style>
